package com.nhncorp.pleiades.protocol;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import com.nhncorp.pleiades.hadoop.Writable;
import com.nhncorp.pleiades.hadoop.WritableUtils;

public class ClientLockInfo implements Writable {
  public static int MAX_META = 1024;
  
  private String creator;
  private String lockId;
  private long lastHeartbeatTime;
  private int lockMode;
  private byte[] metaData;
  
  public ClientLockInfo() { 
  }
  
  public ClientLockInfo(String creator, String lockId) {
    this.creator = creator;
    this.lockId = lockId;    
  }

  public long getLastHeartbeatTime() {
    return lastHeartbeatTime;
  }

  public void setLastHeartbeatTime(long lastHeartbeatTime) {
    this.lastHeartbeatTime = lastHeartbeatTime;
  }

  public String getCreator() {
    return creator;
  }
  
  public void setCreator(String name) {
    this.creator = name;
  }
  
  public String getLockId() {
    return lockId;
  }
  
  public void setLockId(String id) {
    this.lockId = id;
  }
  
  public int getLockMode() {
    return lockMode;
  }
  
  public void setLockMode(int lockMode) {
    this.lockMode = lockMode;
  }
  
  
  public boolean equals(Object obj) {
    if( !(obj instanceof ClientLockInfo) )  return false;
    
    ClientLockInfo otherLockInfo = (ClientLockInfo)obj;
    if(creator.equals(otherLockInfo.creator)) {
      return lockId.equals(otherLockInfo.lockId);
    }
    return false;
  }
  
  
  public int hashCode() {
    return creator.hashCode();
  }
  
  public void readFields(DataInput in) throws IOException {
    creator = WritableUtils.readString(in);
    lockId = WritableUtils.readString(in);
    lockMode = in.readInt();
    lastHeartbeatTime = in.readLong();
    int length = in.readInt();
    if(length > 0) {
      if(length > MAX_META) {
        throw new IOException("Too big meta value:" + length);
      }
      metaData = new byte[length];
      in.readFully(metaData);
    }
  }

  public void write(DataOutput out) throws IOException {
    WritableUtils.writeString(out, creator);
    WritableUtils.writeString(out, lockId);
    out.writeInt(lockMode);
    out.writeLong(lastHeartbeatTime);
    
    int length = 0;
    if(metaData != null) {
      length = metaData.length;
    }
    out.writeInt(length);
    if(length > 0) {
      out.write(metaData);
    }
  }
  
  public String toString() {
    return creator + "," +lockId + "," + lockMode + "," + lastHeartbeatTime;
  }

  public byte[] getMetaData() {
    return metaData;
  }

  public void setMetaData(byte[] metaData) {
    this.metaData = metaData;
  }
}
